import { defineStore } from 'pinia'
import { loginApi, getInfoApi } from '@/api/system/user/user'
import { LoginParam } from '@/api/system/user/UserModel'
import { Result } from '@/http/request'
import { setToken } from '@/utils/auth'

export type UserState = {
    token: string
    permissions: string[]
}

export const userStore = defineStore('userStore', {
    state: (): UserState => {
        return {
            token: '',
            permissions: []
        }
    },
    actions: {
        // 获取用户信息
        getInfo() {
            return new Promise((resolve, reject) => {
                getInfoApi()
                    .then((res) => {
                        //设置权限
                        if (res.code == 200) {
                            this.permissions = res.data.permissions
                        }
                        resolve(res.data)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        },
        // 登录
        login(loginParam: LoginParam) {
            return new Promise<Result>((resolve, reject) => {
                loginApi(loginParam)
                    .then((res) => {
                        // 把返回的token放到vuex里面 和 cookies(sessioStorage)
                        if (res) {
                            this.token = res.data.token
                            // 存到cookies ==> sessioStorage
                            setToken(res.data.token)
                            // setExpireTime(res.data.expiresAt)
                        }
                        resolve(res)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        }
    },
    getters: {
        getToken(state) {
            return state.token
        },
        // 获取用户的权限字段
        getPermissions(state) {
            return state.permissions
        }
    }
})
